# -*- coding: utf-8 -*-
"""
@Time ： 2024/4/19 13:59
@Auth ： RS迷途小书童
@File ：License Plate Recognition.py
@IDE ：PyCharm
@Purpose：车辆拍照识别
@Web：博客地址:https://blog.csdn.net/m0_56729804
"""
import os.path

# 导入cv相关库
import cv2
import random
import warnings
import numpy as np
from PIL import ImageFont
from PIL import Image
from PIL import ImageDraw
import hyperlpr3 as lpr3


class Hyper():
    def __init__(self):
        # 获取上级目录的文件
        font_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + "/resources/simsun.ttc"
        self.font = ImageFont.truetype(font_path, 20, 0)  # 中文字体加载
        self.catcher = lpr3.LicensePlateCatcher(detect_level=lpr3.DETECT_LEVEL_HIGH)  # 实例化识别对象

    def draw_plate_on_image(self, img, box1, text1):
        x1, y1, x2, y2 = box1  # 识别框的四至范围
        # random_color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
        cv2.rectangle(img, (x1, y1), (x2, y2), (0, 0, 255), 2, cv2.LINE_AA)  # 车牌外框
        # cv2.rectangle(img, (x1, y1 - 25), (x2, y1-3), (139, 139, 102), -1)  # 识别文本底色
        data = Image.fromarray(img)  # 读取图片
        draw = ImageDraw.Draw(data)  # PIL绘制图片
        draw.text((x1, y1 - 27), text1, (0, 0, 255), font=self.font)  # 添加识别文本
        res = np.asarray(data)  # 返回叠加识别结果的图片
        return res


    def license_recognition_video(self, path):
        video = cv2.VideoCapture()
        video.open(path)
        i = 0
        while True:
            i += 1
            ref, image = video.read()  # 组帧打开视频
            if ref:
                if i % 10 == 0:
                    results = self.catcher(image)  # 执行识别算法
                    for code, confidence, type_idx, box in results:
                        # [['京Q58A77', 0.9731929, 0, [150, 160, 451, 259]]]
                        text = f"{code} - {confidence:.2f}"
                        image = self.draw_plate_on_image(image, box, text)  # 绘制识别结果
                    cv2.imshow("License Plate Recognition(Directed By RSran)", image)  # 显示检测结果
                    if cv2.waitKey(10) & 0xFF == ord('q'):
                        break  # 退出
            else:
                break


    def license_recognition_image(self, path):
        # 降低图像分辨率
        width = 800  # 新宽度
        height = 600  # 新高度
        dim = (width, height)
        image = cv2.imread(path)  # 读取图片
        image = cv2.resize(image, dim, interpolation=cv2.INTER_AREA)
        results = self.catcher(image)  # 执行识别算法
        text = '未识别到车牌'
        for code, confidence, type_idx, box in results:
            # [['京Q58A77', 0.9731929, 0, [150, 160, 451, 259]]]
            text = f"{code}"
            image = self.draw_plate_on_image(image, box, text)  # 绘制识别结果
        # cv2.imshow("License Plate Recognition(Directed By RSran)", image)  # 显示检测结果
        # cv2.waitKey(0)
        return text


if __name__ == "__main__":
    warnings.filterwarnings("ignore", message="Mean of empty slice")  # 忽略“Mean of empty slice”的警告
    warnings.filterwarnings("ignore", message="invalid value encountered in scalar divide")
    # 忽略“invalid value encountered in scalar divide”的警告
    catcher = lpr3.LicensePlateCatcher(detect_level=lpr3.DETECT_LEVEL_HIGH)  # 实例化识别对象
    file = r"car2.jpg"
    plate = Hyper().license_recognition_image(file)
    print(f'识别到车牌：{plate}')